import { LOADDATA, DECREMENTINVENTORY } from '../actionTypes'

const state = {
  all: []
}

const mutations = {
  setProducts(state, products) {
    state.all = products
  },
  decrementInventory(state, product) {
    const result = state.all.find(p => p.id === product.id)
    result.inventory--
  }
}

const actions = {
  [LOADDATA]({commit}) {
    fetch('/products.json')
      .then(response => response.json())
      .then(result => {
        commit('setProducts', result.data)
      })
  },

  [DECREMENTINVENTORY]({commit}, product) {
    commit('decrementInventory', product)
  }
}

const getters = {

}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}